<template>
  <div class="outsourcing-order-container">
    <!-- 顶部操作按钮 -->
    <div class="action-buttons">
      <!-- <el-button type="primary" @click="AddoutSourOrder()">保存</el-button> -->
      <el-button @click="cancel()">取消</el-button>
      <el-button type="success" @click="approve">审核</el-button>
      <el-button type="warning" @click="rejectApprove">反审核</el-button>
      <!-- <el-button @click="collapse">收起</el-button> -->
    </div>
    <!-- 表单部分 -->
    <el-form :model="formData" class="form-container">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="单据编码">
            <el-input v-model="formData.documentCode" disabled>
              <template #append>
                <el-button type="text" @click="collapseDocumentCode">收缩</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="业务类型">
            <el-select v-model="formData.businessType" disabled>
              <el-option label="委外订单" value="委外订单"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="计划单号">
            <el-input v-model="formData.planOrderNumber" disabled>
              <template #append>
                <el-button type="text" @click="selectPlanNumber()">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="物料编码">
            <el-input v-model="formData.materialCode" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="供方" >
            <el-input v-model="formData.supplier" disabled>
              <template #append>
                <el-button type="text" @click="selectSupplier()">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="单据日期">
            <el-date-picker v-model="formData.documentDate" type="date" disabled placeholder="请选择单据日期"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="操作员">
            <el-input v-model="formData.createdBy" placeholder="操作员" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="销售单号">
            <el-input v-model="formData.salesOrderNumber" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="物料名称">
            <el-input v-model="formData.materialName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="委托合同">
            <el-input v-model="formData.entrustedContract" placeholder="请输入委托合同" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="单据状态">
            <el-input v-model="formData.documentStatus" placeholder="单据状态" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="审核员">
            <el-input v-model="formData.auditor" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="订单交期">
            <el-date-picker v-model="formData.orderDeliveryDate" type="date" disabled></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="规格型号">
            <el-input v-model="formData.specificationModel" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="委外数量">
            <el-input v-model="formData.outsourcingQuantity" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="业务状态">
            <el-select v-model="formData.businessStatus" disabled>
              <el-option label="正常" value="正常"></el-option>
              <el-option label="挂起" value="挂起"></el-option>
              <el-option label="手工关闭" value="手工关闭"></el-option>
              <el-option label="系统关闭" value="系统关闭"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="审核日期">
            <el-date-picker v-model="formData.auditDate" type="date" disabled></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="需求日期">
            <el-date-picker v-model="formData.requirementDate" type="date" placeholder="选择日期" disabled></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="图纸号">
            <el-input v-model="formData.drawingNumber" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="加工费">
            <el-input v-model="formData.processingFee" placeholder="请输入加工费" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注信息">
            <el-input type="textarea" v-model="formData.remarks" placeholder="请输入备注信息" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 发料明细部分 -->
    <div class="material-issuance">
      <div class="section-title">
        <span>发料明细</span>
        <el-button type="text" @click="issueMaterial()">发料</el-button>
      </div>
      <el-table :data="issueMaterialTableData" stripe border>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="documentCode" label="单据编码"></el-table-column>
        <el-table-column prop="documentStatus" label="单据状态"></el-table-column>
        <el-table-column prop="businessStatus" label="业务状态"></el-table-column>
        <el-table-column prop="outsourcingOrderNumber" label="委外单号"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码"></el-table-column>
        <el-table-column prop="materialName" label="物料名称"></el-table-column>
        <el-table-column prop="outsourcingQuantity" label="领用数量">
          <template #default="scope">
            {{10}}
          </template>
        </el-table-column>
        <el-table-column prop="outsourcingQuantity" label="出库数量">
          <template #default="scope">
            {{10}}
          </template>
        </el-table-column>
        <el-table-column prop="documentDate" label="单据日期"></el-table-column>
      </el-table>
    </div>
    <!-- 到货明细部分 -->
    <div class="arrival-material">
      <div class="section-title">
        <span>到货明细</span>
        <el-button type="text" @click="arrivalMaterial()">到货</el-button>
      </div>
      <el-table :data="tableData1" style="width: 100%" border fit  @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="单据编码" prop="documentCode"></el-table-column>
        <el-table-column label="单据日期" prop="documentDate">
          <template #default="scope">
            {{ formatDate(scope.row.documentDate) }}
          </template>
        </el-table-column>
        <el-table-column label="单据状态" prop="documentStatus">
          <template #default="scope">
            <span :style="{color: scope.row.documentStatus === '开立' ? 'orange' : 'green'}">{{ scope.row.documentStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column label="业务类型" prop="businessType"></el-table-column>
        <el-table-column label="业务状态" prop="businessStatus"></el-table-column>
        <el-table-column label="审核日期" prop="auditDate">
          <template #default="scope">
            {{ formatAuditDate(scope.row.auditDate) }}
          </template>
        </el-table-column>
        </el-table>
    </div>
  </div>

  <el-dialog v-model="dialogTableVisible" title="选择计划单" width="1200">
  <div class="search-bar">
    <el-input placeholder="销售单号" v-model="searchParams.salesOrderNo" style="width:150px;margin-right: 15px;"></el-input>
    <el-input placeholder="物料编码" v-model="searchParams.materialCode" style="width:150px;margin-right: 15px;"></el-input>
    <el-input placeholder="物料名称" v-model="searchParams.materialName" style="width:150px;margin-right: 15px;"></el-input>
    <el-date-picker
      v-model="searchParams.startDate"
      type="date"
      placeholder="开始日期"
      style="width: 120px;"
    ></el-date-picker>
    <el-date-picker
      v-model="searchParams.endDate"
      type="date"
      placeholder="结束日期"
      style="width: 120px;margin-right: 20px;"
    ></el-date-picker>
    <el-button type="primary" @click="search" style="margin-right: 20px;">搜索</el-button>
    <el-button type="primary" @click="resetSearch">查看所有</el-button>
  </div>
  <el-table :data="gridData" @selection-change="handleSelectionChange">
    <el-table-column type="selection"></el-table-column>
    <el-table-column property="salesOrderNo" label="销售单号" width="150" />
    <el-table-column property="orderDeliveryDate" label="订单交期" width="150" />
    <el-table-column property="planOrderNo" label="计划单号" width="150" />
    <el-table-column property="materialCode" label="物料编码" width="150" />
    <el-table-column property="materialName" label="物料名称" />
    <el-table-column property="guige" label="规格型号" />
    <el-table-column property="mainMeasurement" label="主计量" width="100" />
    <el-table-column property="plannedQuantity" label="计划数量" width="100" />
    <el-table-column property="producedQuantity" label="已生产量" width="100" />
    <el-table-column property="unproducedQuantity" label="未生产量" width="100" />
    <el-table-column property="demandDate" label="需求日期" width="150" />
    <el-table-column property="tuzhi" label="图纸号" width="150" />
  </el-table>
  <div class="pagination">
    <el-pagination
    v-model:current-page="currentPage4"
    v-model:page-size="pageSize4"
    :page-sizes="[15, 20, 30, 40]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="1"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    prev-text="上一页"
    next-text="下一页"
  />
  </div>
  <div class="action-buttons">
    <el-button type="primary" @click="jihuadanhao()">确定</el-button>
    <el-button @click="cancel">取消</el-button>
  </div>
</el-dialog>

<el-dialog v-model="dialogVisible1" title="选择供应商" width="800px">
  <div class="search-bar">
    <!-- <el-input v-model="searchForm.supplierName" placeholder="供应商名称" style="width:150px;margin-right: 15px;"></el-input>
    <el-input v-model="searchForm.contactPerson" placeholder="业务联系人" style="width:150px;margin-right: 15px;"></el-input>
    <el-button type="primary" @click="search">搜索</el-button>
    <el-button type="success" @click="quickAdd">+ 快速添加</el-button>
    <el-button type="text" @click="resetSearch">查看所有</el-button> -->
  </div>
  <el-table :data="tableData" border>
    <el-table-column type="index" label="序号" width="50"></el-table-column>
    <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
    <el-table-column prop="phone" label="电话"></el-table-column>
    <el-table-column prop="contactPerson" label="业务联系人"></el-table-column>
    <el-table-column prop="mobile" label="手机号"></el-table-column>
    <el-table-column prop="supplyCategory" label="供应料品"></el-table-column>
    <el-table-column label="状态">
      <template #default="scope">
        <el-switch v-model="scope.row.status"></el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="80">
      <template #default="scope">
        <el-button type="text" size="small" @click="selectSupplier1(scope.row)">选择</el-button>
      </template>
    </el-table-column>
  </el-table>

    <el-pagination
    v-model:current-page="currentPage4"
    v-model:page-size="pageSize4"
    :page-sizes="[10, 20, 30, 40]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="1"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    prev-text="上一页"
    next-text="下一页"
  />

</el-dialog>

</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage ,ElMessageBox} from 'element-plus';
import {useRoute,useRouter} from 'vue-router'
import { saveAs } from 'file-saver';
import {KongaUrl} from '@/axios/axiosHelp';

let route=useRoute();
let router=useRouter();

onMounted(()=>{
  fantian();
})
const fantian=()=>{
KongaUrl({
      url:'/weiwaidu/api/OutSourc/GetOutsourOrderID',
      method:'get',
      params:{
          id:route.query.id
      }
  })
  .then(res=>{
      if(res.data.code==101){
          console.log(res.data.list)
          formData.id=route.query.id;
          formData.documentCode=res.data.list[0].documentCode
          formData.businessType=res.data.list[0].businessType
          formData.planOrderNumber=res.data.list[0].planOrderNumber
          formData.materialCode=res.data.list[0].materialCode
          formData.supplier=res.data.list[0].supplier
          formData.documentDate=res.data.list[0].documentDate
          formData.operator=res.data.list[0].operator
          formData.salesOrderNumber=res.data.list[0].salesOrderNumber
          formData.materialName=res.data.list[0].materialName
          formData.entrustedContract=res.data.list[0].entrustedContract
          formData.documentStatus=res.data.list[0].documentStatus
          formData.auditor=res.data.list[0].auditor
          formData.orderDeliveryDate=res.data.list[0].orderDeliveryDate
          formData.specificationModel=res.data.list[0].specificationModel
          formData.outsourcingQuantity=res.data.list[0].outsourcingQuantity
          formData.businessStatus=res.data.list[0].businessStatus
          formData.auditDate=res.data.list[0].auditDate
          formData.requirementDate=res.data.list[0].requirementDate
          formData.drawingNumber=res.data.list[0].drawingNumber
          formData.processingFee=res.data.list[0].processingFee
          formData.remarks=res.data.list[0].remarks
          formData.createdDate=res.data.list[0].createdDate
          formData.createdBy=res.data.list[0].createdBy
          formData.modifiedDate=res.data.list[0].modifiedDate
          formData.modifiedBy=res.data.list[0].modifiedBy
          formData.isDelete=res.data.list[0].isDelete
      }
  })
}

const dialogTableVisible = ref(false);
const searchParams = ref({
salesOrderNo: '',
materialCode: '',
materialName: '',
startDate: '',
endDate: ''
});
// 控制对话框显示隐藏
const dialogVisible1 = ref(false);
// 搜索表单数据
const searchForm = ref({
supplierName: '',
contactPerson: ''
});
// 表格数据（模拟数据，实际需从后端获取）
const tableData = ref([
{
  id: 1,
  supplierName: '南京宇创石化工程有限公司',
  phone: '18936886533',
  contactPerson: '',
  mobile: '',
  supplyCategory: '',
  status: true
},
// 可继续添加更多模拟数据
]);

// 表单数据
const formData = reactive({
  id:route.query.id,
  documentCode:`WWDJ${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`,
  businessType: '委外订单',
  planOrderNumber: '',
  materialCode: '',
  supplier: '',
  documentDate: new Date('2025-04-25'),
  createdBy: 'njrsun',
  salesOrderNumber: '',
  materialName: '',
  entrustedContract: '',
  documentStatus: '开立',
  auditor: '',
  RequirementDate:Date,
  auditDate:Date,
  orderDeliveryDate: '',
  specificationModel: '',
  outsourcingQuantity: '',
  businessStatus: '正常',
  drawingNumber: '',
  processingFee: '',
  remarks: '',
  modifiedBy:'',
  operator:'njrsun',
  
})

const AddoutSourOrder=()=>{
  KongaUrl({
      url:'/weiwaixie/api/Outsour/UpdateOutSourOrder',
      method:'post',
      data:formData
  }).then(res=>{
      if(res.data.code==101){
          ElMessage.success("操作成功");
          router.push("/OutSourOrderShow")
      }
  })
}
const palosp=reactive({
  Pid:route.query.id,
  pageindex:1,
  pagesize:15
})
const queryOutsourRelease=()=>{
  axios({
    url:'http://localhost:5027/api/OutSourc/QueryOutSourReleasePid',
    method:'get',
    params:{
      Pid:palosp.Pid,
      pageindex:palosp.pageindex,
      pagesize:palosp.pagesize,
    }
  }).then(res=>{
   if(res.data.code==0){
    issueMaterialTableData.value=res.data.list;
    console.log('发料明细',issueMaterialTableData.value);
   }
  })
}

// 发料明细表格数据
const issueMaterialTableData = ref([])
// 到货明细表格数据
const arrivalMaterialTableData = ref([])

// 取消方法
const cancel = () => {
 router.push("/OutSourOrderShow")
}
// 审核方法
const approve = () => {
  console.log('审核操作')
  // 可添加调用后端接口审核等逻辑
}
// 反审核方法
const rejectApprove = () => {
  console.log('反审核操作')
  // 可添加调用后端接口反审核等逻辑
}
// 收起方法
const collapse = () => {
  console.log('收起操作')
  // 可添加控制表单收缩等逻辑
}
// 收缩单据编码方法
const collapseDocumentCode = () => {
  console.log('收缩单据编码操作')
}
// 选择计划单号方法
const selectPlanNumber = () => {
  dialogTableVisible.value=true;
}
// 选择供方方法
const selectSupplier = () => {
  dialogVisible1.value=true;
}
const selectSupplier1=(row)=>{
  formData.supplier=row.supplierName
  console.log('供方那个名称',formData.supplier)
  dialogVisible1.value=false;
}
// 发料方法
const issueMaterial = () => {
  router.push({
    name:'AddOutSourRelease',
    query:{  
      id:route.query.id,
      documentCode:formData.documentCode,
      businessType:formData.businessType,
      planOrderNumber:formData.planOrderNumber,
      materialCode:formData.materialCode,
      supplier:formData.supplier,
      documentDate:formData.documentDate,
      createdBy:formData.createdBy,
      salesOrderNumber:formData.salesOrderNumber,
      materialName:formData.materialName,
      entrustedContract:formData.entrustedContract,
      documentStatus:formData.documentStatus,
      auditor:formData.auditor,
      orderDeliveryDate:formData.orderDeliveryDate,
      specificationModel:formData.specificationModel,
      outsourcingQuantity:formData.outsourcingQuantity,
      businessStatus:formData.businessStatus,
      drawingNumber:formData.drawingNumber,
      processingFee:formData.processingFee,
      remarks:formData.remarks,
      createdDate:formData.createdDate,
      createdBy:formData.createdBy,
      modifiedDate:formData.modifiedDate,
      modifiedBy:formData.modifiedBy,
      isDelete:formData.isDelete,
      requirementDate:formData.requirementDate,
      
    }
  })
  console.log('发料操作',route.query)
  // 可添加调用后端接口发料等逻辑
}
// 到货方法
const arrivalMaterial = () => {
  router.push({
    name:'AddOutsourceddelivery',
    query:{
      id:route.query.id,
      documentCode:formData.documentCode,
      businessType:formData.businessType,
      planOrderNumber:formData.planOrderNumber,
      materialCode:formData.materialCode,
      supplier:formData.supplier,
      documentDate:formData.documentDate,
      createdBy:formData.createdBy,
      salesOrderNumber:formData.salesOrderNumber,
      materialName:formData.materialName,
      entrustedContract:formData.entrustedContract,
      documentStatus:formData.documentStatus,
      auditor:formData.auditor,
      orderDeliveryDate:formData.orderDeliveryDate,
      specificationModel:formData.specificationModel,
      outsourcingQuantity:formData.outsourcingQuantity,
      businessStatus:formData.businessStatus,
      drawingNumber:formData.drawingNumber,
      processingFee:formData.processingFee,
      remarks:formData.remarks,
      createdDate:formData.createdDate,
      createdBy:formData.createdBy,
      modifiedDate:formData.modifiedDate,
      modifiedBy:formData.modifiedBy,
      isDelete:formData.isDelete,
      requirementDate:formData.requirementDate,
    }
  })
  console.log('到货操作')
  // 可添加调用后端接口到货等逻辑
}
// 计划模拟数据
const gridData = ref([
{
  saleOrderid:1,
  salesOrderNo: 'XSBH000002',
  orderDeliveryDate: '2025-4-27',
  planOrderNo: 'SCJH000014',
  materialCode: '0101000001',
  materialName: '118S ZY型纸杯机',
  guige:'ZY型',
  mainMeasurement: '台',
  plannedQuantity: 222.00,
  producedQuantity: 0.00,
  unproducedQuantity: 222.00,
  demandDate: '',
  tuzhi:'118S'
}
]);

const jihuadanhao=()=>{
if (!selectedPlan.value) {
  ElMessage.warning('请先选择计划单')
  return
}

console.log(selectedIds.value)
formData.planOrderNumber=`SCJH${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`
formData.materialCode=selectedPlan.value.materialCode 
formData.salesOrderNumber=selectedPlan.value.salesOrderNo 
formData.materialName=selectedPlan.value.materialName 
formData.orderDeliveryDate=selectedPlan.value.orderDeliveryDate 
formData.specificationModel=selectedPlan.value.guige  
formData.demandDate=selectedPlan.value.demandDate 
formData.drawingNumber=selectedPlan.value.tuzhi 
formData.outsourcingQuantity=selectedPlan.value.unproducedQuantity 
console.log('销售单号',formData.salesOrderNumber)
dialogTableVisible.value=false;

}
const selectedIds=reactive([]);
const selectedPlan=ref([])
// 选择项变化
const handleSelectionChange = (val) => {
if (val.length > 1) {
  ElMessage.warning('请选择单条计划数据')
  return
}
selectedPlan.value = val[0] || null  // 存储第一个选中项
selectedIds.value = val
// .map(item => item.saleOrderid)
console.log('选中的数据', selectedIds.materialCode)
}
onMounted(()=>{
queryAll();
queryOutsourRelease();
})
const tableData1=ref([]);
// 搜索表单数据
const searchForm1 = reactive({
pid:route.query.id,
followOrderNumber: '',
documentCode: '',
materialCode: '',
materialName: '',
startDate: '',
endDate: '',
pageindex:1,
pagesize:15
});
// 格式化日期函数
const formatDate = (date) => {
if (!date) return '';
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
// 格式化审核日期，1900-1-1不显示
const formatAuditDate = (date) => {
if (!date) return '';
const d = new Date(date);
if (d.getFullYear() === 1900 && d.getMonth() === 0 && d.getDate() === 1) return '';
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
// 查询所有方法
const queryAll = () => {
axios({
  url:'http://localhost:5027/api/OutSourc/QuertOutArrial',
  method:'get',
  params:{
    Pid:searchForm1.pid,
    DocumentCode:searchForm1.documentCode,
    MaterialCode:searchForm1.materialCode,
    MaterialName:searchForm1.materialName,
    StartDate:searchForm1.startDate,
    EndDate:searchForm1.endDate,
    pageindex:searchForm1.pageindex,
    pagesize:searchForm1.pagesize
  }
})
.then(res=>{
  if(res.data.code==101){
   
    tableData1.value=res.data.list;
    console.log('到货明细',tableData1.value);
  }
  
})
};
</script>

<style scoped>
.outsourcing-order-container {
  padding: 20px;
}
.action-buttons {
  margin-bottom: 20px;
  text-align: right;
}
.form-container {
  border: 1px solid #e4e7ed;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}
.material-issuance,
.arrival-material {
  border: 1px solid #e4e7ed;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}
.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>    